package com.returnsoft.softphone.controller;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.websocket.EncodeException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;




@ServerEndpoint(value = "/pbxendpoint/{client-id}")
public class PbxServer {
	

	private static Map<Integer, Session> sessions = Collections
			.synchronizedMap(new HashMap<Integer, Session>());
	
	
	public PbxServer(){
		System.out.println("Ingreso al constructor PbxServer");
	
		
		
	}

	@OnMessage
	public void onMessage(final Session session, final String message,
			@PathParam("client-id") Integer agentId) {
		
		

		System.out.println("en el server: onMessage"+message);
		
		String idAgent=message.substring(0,message.indexOf(":"));
		
		String text =message.substring(message.indexOf(":")+1);
		
		if (idAgent!=null && idAgent.length()>0) {
			Integer idAgentInt = Integer.parseInt(idAgent);
			System.out.println("idAgent:"+idAgentInt);
			Session sessionFound = sessions.get(idAgentInt);
			if (sessionFound!=null) {
				sendMessage(sessionFound, text);
			}
		}
		
		
		
		
		
		//Session sessionDestiny = sessions.get(agentId);
		
		//sendMessage(sessionDestiny, message);
		

	}

	@OnOpen
	public void onOpen(Session session, @PathParam("client-id") Integer clientId) {
		System.out.println("en el server: onOpen clientId: " + clientId);
		//ADD CHATTER
		sessions.put(clientId, session);
		
		
	}

	@OnClose
	public void onClose(Session session, @PathParam("client-id") Integer clientId) {
		System.out.println("en el server: onClose, clientId: " + clientId);
		Iterator<Entry<Integer,Session>> sesiones = sessions.entrySet().iterator();
		while(sesiones.hasNext()){
			Entry<Integer,Session> entry = sesiones.next();	
			//System.out.println("COMPARANDO:"+entry.getValue().getId()+"TO"+session.getId());
			if (entry.getValue().getId().equals(session.getId())) {
				//REMOVE CHATTER
				sessions.remove(entry.getKey());
				//SEND BROADCAST

			}
		}
		
	}

	
	public void sendMessage(Session session, String message) {
		try {
			System.out.println("Ingreso a sendMessage");
			session.getBasicRemote().sendObject(message);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (EncodeException e) {
			e.printStackTrace();
		}
	}

	
	


}
